<?php 
defined('ACC')||exit('ACC Denied');
class Mysql extends db{ 
	private static $ins=null;
	protected $dbh = null;
	private $conf=array();
	/**
	 * Mysql constructor.
	 */
	protected function __construct(){
		$this->conf=conf::getIns();
		try{
			$this->dbh = new PDO($this->data['mysql'],$this->conf->user,$this->conf->pwd);}
		catch(PDOException $e){
			echo '数据库连接失败'.$e->getMessage();
		}
		$this->query('set names utf8');
	}
	/**
	 * @return Mysql|null
	 */
	public static function getIns(){
		if (self::$ins instanceof self) {
			return self::$ins;
		}
			self::$ins=new self();
			return self::$ins;
		
	}
	/**
	 * @param $sql
	 * @return int
	 */
	public function exec($sql){
		$rs=$this->dbh->exec($sql);
		if (!$rs) {
			Log::write($sql."\n".implode(',',$this->dbh->errorInfo())."\n".'时间：'.gmdate('y/m/d h:i:s',time()+8*3600));
		}else{
		Log::write($sql."\n".implode(',',$this->dbh->errorInfo())."\n".'时间：'.gmdate('y/m/d h:i:s',time()+8*3600));
	}
		return $rs;
	}

	/**
	 * @param $sql
	 * @return PDOStatement
	 */
	public function query($sql){//当执行返回结果集的select查询时，该方法执行成功，返回一个PDOstatement对象
		$stmt=$this->dbh->query($sql);
		if (!$stmt) {
			Log::write($sql."\n".implode(',',$this->dbh->errorInfo())."\n".'时间：'.gmdate('y/m/d h:i:s',time()+8*3600));
		}else{
			Log::write($sql."\n".implode(',',$this->dbh->errorInfo())."\n".'时间：'.gmdate('y/m/d h:i:s',time()+8*3600));//这里把错误的和正确的sql语句都记录进去了；
		}
		return $stmt;
	}
	/**
	 * @param $sql
	 * @return array
	 */
	public function getAll($sql){
		$stmt=$this->query($sql);
		if (!$stmt) {
			echo '错误';
			exit;
		}
		$data=array();
		while ($all= $stmt->fetch(PDO::FETCH_ASSOC)) {
			$data[]=$all;
		}
		return $data;
	}

	/**
	 * @param $sql
	 * @return array
	 */
	public function getOne($sql){//取一行赋给$row;
		$stmt=$this->query($sql);
		$row=$stmt->fetchAll(PDO::FETCH_ASSOC);
		return $row;
	}
	/**
	 * @param $table
	 * @param $arr
	 * @param string $mode
	 * @param string $where
	 * @return bool|int
	 */
	public function autoExecute($table,$arr,$mode='insert',$where='where 1 limit 1'){
		if (!is_array($arr)) {
			return false;
		}
		//insert ino tbname (username,passwd,emali)values('',)
		//把所有的键名用','接起来。
		//implode(',',array_keys($arr));
		//implode("'.'",array_values($arr)
		elseif(is_array($arr)){
		if ($mode=='update') {
			$sql='update '.$table.' set ';
			foreach ($arr as $key => $value) {
				$sql.=$key."='".$value."',";
				}
			$sql=rtrim($sql,',');
			$sql.=$where;
			return $this->exec($sql);
			}
		else{
		$sql='insert into '.$table.' ('.implode(',',array_keys($arr)).')';
		$sql.=' values '.'(\'';
		$sql.=implode("','", $arr).'\')';
		return $this->exec($sql);
			}
		}
	}
}